#include<bits/stdc++.h>
#define int long long
using namespace std;
vector<vector<int>> adj;
vector<bool> vis;
int dfs(int x, int p) {
int ret=1;
vis[x]=1;
for(int pp : adj[x]) {
if(pp==p) continue;
if(vis[pp]) continue;
ret+=dfs(pp, x);
} return ret;
}
int solve() {
int n; cin >> n;
adj.resize(n); vis.resize(n);
vector<int> a(n);
for(int &p : a) cin >> p, --p;
for(int i=0; i<n; i++) {
int p; cin >> p; --p;
adj[p].push_back(a[i]);
adj[a[i]].push_back(p);}
priority_queue<int> pq;
for(int i=0; i<n; i++) {
if(vis[i]) continue;
int bro=dfs(i, -1);
if(bro>1) pq.push(bro);}
int ans=0, i=0, l=1, r=n, par=0, midL=n/2, midR=n/2+1, midPar=0;
while(!pq.empty()) {
int sz=pq.top(); pq.pop();
vector<int> b(sz/2*2);
for(int &p : b) {
if(par) p=(l++);
else p=(r--);
par^=1;}
if(sz&1) {
if(midPar) b.push_back(midL--);
else b.push_back(midR++);
midPar^=1;}
for(int i=1; i<b.size(); i++) ans+=abs(b[i]-b[i-1]);
ans+=abs(b[b.size()-1]-b[0]);
}
adj.clear(); vis.clear();
return ans;
}
signed main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int _; cin >> _;
while(_--) cout << solve() << '\n';
return 0;
}
380. Insert Delete GetRandom O(1) | 332. Reconstruct Itinerary |
368. Largest Divisible Subset | 377. Combination Sum IV |
322. Coin Change | 307. Range Sum Query - Mutable |
287. Find the Duplicate Number | 279. Perfect Squares |
275. H-Index II | 274. H-Index |
260. Single Number III | 240. Search a 2D Matrix II |
238. Product of Array Except Self | 229. Majority Element II |
222. Count Complete Tree Nodes | 215. Kth Largest Element in an Array |
198. House Robber | 153. Find Minimum in Rotated Sorted Array |
150. Evaluate Reverse Polish Notation | 144. Binary Tree Preorder Traversal |
137. Single Number II | 130. Surrounded Regions |
129. Sum Root to Leaf Numbers | 120. Triangle |
102. Binary Tree Level Order Traversal | 96. Unique Binary Search Trees |
75. Sort Colors | 74. Search a 2D Matrix |
71. Simplify Path | 62. Unique Paths |